package com.rising.face.bytes.P5_二叉树的遍历;

import com.rising.leetcode.editor.cn.doc.object.TreeNode;

import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @Author: rising
 * @Description:
 * @Date: create in 2023/1/17 18:22
 */
public class LevelOrder {

    /**
     * 利用两个队列
     * @param node
     * @return
     */
    public List<List<Integer>> levelOrder(TreeNode node) {
        Deque<TreeNode> queue1 = new LinkedBlockingDeque<>();
        Deque<TreeNode> queue2 = new LinkedBlockingDeque<>();
        queue1.add(node);

        List<List<Integer>> rtnList = new LinkedList<>();

        while (!queue1.isEmpty()) {
            List<Integer> temp = new LinkedList<>();
            while (!queue1.isEmpty()) {
                TreeNode first = queue1.removeFirst();
                temp.add(first.val);
                if (first.left != null) queue2.addLast(first.left);
                if (first.right != null) queue2.addLast(first.right);
            }
            queue1.addAll(queue2);
            queue2.clear();
            rtnList.add(temp);
        }
        return rtnList;
    }

    /**
     * 锯齿形遍历
     * @param root
     * @return
     */
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        Deque<TreeNode> queue1 = new LinkedBlockingDeque<>();
        Deque<TreeNode> queue2 = new LinkedBlockingDeque<>();
        queue1.add(root);
        boolean flag = true;
        List<List<Integer>> rtnList = new LinkedList<>();

        while (!queue1.isEmpty()) {
            List<Integer> temp = new LinkedList<>();
            while (!queue1.isEmpty()) {
                TreeNode first = null;
                if (flag) {
                    first = queue1.removeFirst();
                } else {
                    first = queue1.removeLast();
                }
                temp.add(first.val);
                if (first.left != null) queue2.addLast(first.left);
                if (first.right != null) queue2.addLast(first.right);
            }
            queue1.addAll(queue2);
            queue2.clear();
            rtnList.add(temp);
            flag = !flag;
        }
        return rtnList;
    }

    public static void main(String[] args) {

    }
}
